'user strict'
var url = require('url');
var cheerio = require('cheerio');
var request = require('request');
var iconv = require('iconv-lite');
var BufferHelper = require('bufferhelper');
var fs = require('fs');
var querystring = require('querystring');
var _async = require('async');
var jRequest = request.defaults({jar: true});

var exp = {
    loginFetchData: function (userName, password, cookie, verifyCode, viewState, loginUrl, entryUrl, txtusername, txtpassword, txtsecretcode, callback) {
        _async.waterfall([
            _async.apply(studentLogin, userName, password, cookie, verifyCode, viewState, loginUrl, entryUrl, txtusername, txtpassword, txtsecretcode),
            studentInformation,
            courseInformation
        ], function (err, result) {
            if (err) {
                console.log(err);
                callback(err);
                return;
            } else {
                callback(null, result);
                return;
            }
        });
    }
};

function studentLogin(userName, password, cookie, verifyCode, viewState, loginUrl, entryUrl, txtusername, txtpassword, txtsecretcode, callback) {
    var postData = initPostData(userName, password, verifyCode, viewState, txtusername, txtpassword, txtsecretcode);
    console.log("Fectch Data from JWC: " + entryUrl + " by student :" + userName);

    jRequest
        .post({//登陆请求
            url: loginUrl,
            Referer: entryUrl,
            form: postData,
            followAllRedirects: true
        }, function (err, res, body) {
            if (err) {
                console.error(err);
                callback(new Error("登录教务系统失败，请重试"));
            }
            if (res.statusCode == 200) {
                if (body.match(/defer>alert/)) {
                    console.log("Login failed, it may due to wrong check code entered");
                    callback(new Error("登录教务系统失败，请重试"));
                    return;
                }
                console.log("Logged in successfully");
                var $ = cheerio.load(body);
                var rawQs = {
                    "xh": userName,//学号/工号 &xh=username
                    "gnmkdm": "N121501"//选课情况按钮编码 &gnmkdm=N122304
                };

                var queryUrl = entryUrl + cookie + "xsgrxx.aspx?" + querystring.stringify(rawQs) + "&xm=%C4%C2%D3%C0%EA%CD";//xm= 用户姓名 gb2312编码

                callback(null, userName, password, entryUrl, queryUrl, cookie);
            } else {
                callback(new Error("登录教务系统失败，请重试"));
            }
        });




}

function studentInformation(userName, password, entryUrl, queryUrl, cookie, callback) {
    jRequest.get({//获取个人信息
        url: queryUrl,
        encoding: null,
        headers: {
            Referer: entryUrl + cookie + "xs_main.aspx?xh=" + userName
        }
    }, function (err, res, body) {
        if (err) {
            console.log(err);
            callback(new Error("绑定个人信息失败，请重试"));
            return;
        }
        if (res.statusCode != 200) {
            console.log("获取教务系统个人信息页面失败");
            callback(new Error("绑定个人信息失败，请重试"));
            return;
        }

        var recoded_html = resolveGB2312Html(body);
        var $ = cheerio.load(body);
        var $recoded = cheerio.load(recoded_html);
        var ele = $recoded('table[class=formlist]').html();
        var $ele = cheerio.load(ele);

        var xh = $ele('td #xh').text();//学号
        var xm = $ele('td #xm').text();//姓名
        var birth = $ele('td #lbl_csrq').text();//出生日期
        var sfzh = $ele('td #lbl_sfzh').text();//身份证号
        var zy = $ele('td #lbl_zymc').text(); //专业名称
        var cc = $ele('td #lbl_CC').text();//学历层次
        var classname = $ele('td #lbl_xzb').text();//班级名称
        var xy = $ele('td #lbl_xy').text();//学院名称
        var zymc = $ele('td #lbl_zymc').text();//专业名称
        var rxrq = $ele('td #lbl_rxrq').text();//入学日期
        var sex = $ele('td #lbl_xb').text();//性别
        var xz = $ele('td #lbl_xz').text();//学制
        var dqszj = $ele('td #lbl_dqszj').text();//当前所在级
        var mz = $ele('td #lbl_mz').text();//民族

        var personInfo = {
            xh:xh,
            xm:xm,
            birth:birth,
            zy:zy,
            classname:classname,
            xy:xy,
            zymc:zymc,
            sex:sex
        }


        callback(null, userName, entryUrl, personInfo);




    });
}



function courseInformation(userName, entryUrl, personInfo, callback) {
    var rawQs = {
        "xh": userName,//学号/工号 &xh=username
        "gnmkdm": "N21615"//选课情况按钮编码 &gnmkdm=N122304
    };

    var queryUrl = entryUrl + "xsxkqk.aspx?" + querystring.stringify(rawQs) + "&xm=%C4%C2%D3%C0%EA%CD";//xm= 用户姓名 gb2312编码
    jRequest.get({//获取个人信息
        url: queryUrl,
        encoding: null,
        headers: {
            Referer: entryUrl + "xs_main.aspx?xh=" + userName
        }
    }, function (err, res, body) {
        if (err) {
            console.log(err);
            callback(new Error("绑定课程信息失败，请重试"));
            return;
        }
        if (res.statusCode != 200) {
            console.log("获取教务系统课程信息页面失败");
            callback(new Error("绑定课程信息失败，请重试"));
            return;
        }

        var recoded_html = resolveGB2312Html(body);
        var $ = cheerio.load(recoded_html);
        var courseInfo = [];
        $('table[id=DBGrid] tr').each(function (i, ele) {
            if (i == 0) return;//去掉表头
            var $ele = cheerio.load(ele);
            courseInfo.push({
                coursename:$ele("td").eq(2).text(),
                teachername:$ele("td").eq(5).text(),
                time:$ele("td").eq(8).text().replace(/[\r\n\t]+/g,''),
                address:$ele("td").eq(9).text().replace(/[\s]+/g,'')
            })

        });
        var result = [];
        result.push(courseInfo);
        result.push(personInfo);
        // var result = {
        //     courseInfo:courseInfo,
        //     personInfo:personInfo
        // }
        callback(null, courseInfo);

    });
}


function resolveGB2312Html(buffer) {
    var bufferHelper = new BufferHelper();
    bufferHelper.concat(buffer);
    return iconv.decode(bufferHelper.toBuffer(), 'gb2312').toString();
}

function initPostData(userName, password, verifyCode, viewState, txtusername, txtpassword, txtsecretcode) {
    var rawPost = {
        __VIEWSTATE: viewState,
        txtUserName: userName,
        TextBox2: password,
        txtSecretCode: verifyCode,
        Button1: "",
        lbLanguage: "",
        hidPdrs: "",
        hidsc: ""
    };
    var postData = querystring.stringify(rawPost);
    postData += "&RadioButtonList1=%D1%A7%C9%FA";

    return postData;
}

module.exports = exp;
